package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.HotArticleService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.jbf.apis.wemedia.IWemediaClient;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //查询前五天的文章
        Date dayParam = DateTime.now().minusDays(5).toDate();
//        // 转换为只包含日期的字符串
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String dayParam = sdf.format(date);
        List<ApArticle> apArticles = articleMapper.selectArticleByFiveDayAgo(dayParam);
        if (CollectionUtils.isEmpty(apArticles)){
            throw new RuntimeException("文章不存在");
        }
        //计算他们的分值
        List<HotArticleVo> HotArticleList=computeHotArticle(apArticles);

        //为每个频道缓存三十条分值高的文章
        HotArticleList=HotArticleList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (HotArticleList.size()>30){
            HotArticleList = HotArticleList.subList(0, 30);
        }
        ResponseResult channels = wemediaClient.getChannels();
        String jsonString = JSON.toJSONString(channels.getData());
        List<WmChannel> wmChannels = JSONObject.parseArray(jsonString, WmChannel.class);
        for (WmChannel wmChannel : wmChannels) {
            List<HotArticleVo> list = HotArticleList.stream().filter(item -> item.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(list)){
                cacheService.set("hotChannel:"+wmChannel.getId(),JSON.toJSONString(list));
            }
        }
//        HotArticleList.forEach(item->{
//            cacheService.set("hotChannel:"+item.getChannelId(),JSON.toJSONString(item));
//        });
        cacheService.set("recommend", JSON.toJSONString(HotArticleList));


    }

    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticles) {
        return apArticles.stream().map(item -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(item, hotArticleVo);
            Integer score=computeScore(item);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算文章分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer collection = apArticle.getCollection();//收藏
        Integer comment = apArticle.getComment();//评论
        Integer likes = apArticle.getLikes();//点赞
        Integer views = apArticle.getViews();//阅读数
        Integer score=0;
        if (collection!=null){
            score=score+collection*8;
        }
        if (comment!=null){
            score=score+comment*5;
        }
        if (likes!=null){
            score=score+likes*3;
        }
        if (views!=null){
            score=score+views*1;
        }
        return score;

    }
}
